﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Dominio;
using LogicaNegocios.Manager;

namespace UIWeb
{
    public partial class Default_seguidores : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            UsuarioManager um = UsuarioManager.GetManager();
            if (Session["userLogin"] == null)
            {
                Response.Redirect("~/UserLogin.aspx");
            }
            else
            {
                if (um.esAdmin((Usuario)Session["userLogin"]))
                    Response.Redirect("~/Default.aspx");


            }
            if (!IsPostBack)
            {

                DateTime dateNow = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddDays(-1);
                LoadCalendarEvents(dateNow);
                LoadMedallero();

                Usuario usuario = (Usuario)Session["userLogin"];
                LoadMsg(usuario.NombreUsuario); //para probar, luego pasar usuario.id cómo parámetro
                cargarGrid();
            }
        }

        #region medallero
        private void LoadMedallero()
        {
            DataSet ds = ReporteManager.GetManager().GetStoreProcedureMedallero();
            if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
            {

                DataTable dtTemp1 = ds.Tables[0].DefaultView.ToTable(true, new string[] { "cantOro", "nombrepais" });
                DataTable dtTemp2 = ds.Tables[1].DefaultView.ToTable(true, new string[] { "cantPlata", "nombrepais" });
                DataTable dtTemp3 = ds.Tables[2].DefaultView.ToTable(true, new string[] { "cantBronce", "nombrepais" });
                DataTable dtTemp4 = ds.Tables[3].DefaultView.ToTable(true, new string[] { "cantOro", "nombrepais" });
                DataTable dtTemp5 = ds.Tables[4].DefaultView.ToTable(true, new string[] { "cantPlata", "nombrepais" });
                DataTable dtTemp6 = ds.Tables[5].DefaultView.ToTable(true, new string[] { "cantBronce", "nombrepais" });

                StringBuilder sb = new StringBuilder();
               
                ParticipanteManager pm = ParticipanteManager.GetManager();

                    List<Pais> listPaises = pm.GetPaises();
                    foreach (Pais pais in listPaises)
                    {
                        string nombrePais = pais.Nombre;
                        int oro = 0;
                        int plata = 0;
                        int bronce = 0;
                        int total = 0;
                        foreach (DataRow r in dtTemp1.Rows)
                        {
                            if(r["nombrePais"].ToString().CompareTo(nombrePais) ==0)
                               if(r["cantOro"].ToString().CompareTo("0") != 0)
                                 oro = oro +1;
                        }
                        foreach(DataRow r in dtTemp2.Rows)
                        {
                             if(r["nombrePais"].ToString().CompareTo(nombrePais) ==0)
                                 if (r["cantPlata"].ToString().CompareTo("0") != 0)
                                plata = plata+1;
                        
                        }
                        foreach(DataRow r in dtTemp3.Rows)
                        {
                             if(r["nombrePais"].ToString().CompareTo(nombrePais) ==0)
                                 if (r["cantBronce"].ToString().CompareTo("0") != 0)
                                bronce = bronce+1;
                        
                        }
                        
                        foreach(DataRow r in dtTemp4.Rows)
                        {
                             if(r["nombrePais"].ToString().CompareTo(nombrePais) ==0)
                                 if (r["cantOro"].ToString().CompareTo("0") != 0)
                                oro = oro+1;
                        
                        }

                        foreach(DataRow r in dtTemp5.Rows)
                        {
                             if(r["nombrePais"].ToString().CompareTo(nombrePais) ==0)
                                 if (r["cantPlata"].ToString().CompareTo("0") != 0)
                                plata = plata+1;
                        
                        }

                        foreach(DataRow r in dtTemp6.Rows)
                        {
                             if(r["nombrePais"].ToString().CompareTo(nombrePais) ==0)
                                 if (r["cantBronce"].ToString().CompareTo("0") != 0)
                                bronce = bronce+1;
                        
                        }
                        
                        total = oro + plata + bronce;
                    
                            sb.Append("<tr>");
                            sb.Append("<td class='tdCountryBody'>" + nombrePais + "</td>");
                            sb.Append("<td class='tdMedal'>" + oro.ToString()  + "</td>");
                            sb.Append("<td class='tdMedal'>" + plata.ToString() + "</td>");
                            sb.Append("<td class='tdMedal'>" + bronce.ToString() + "</td>");
                            sb.Append("<td>" + total.ToString() +  "</td>");
                            sb.Append("</tr>");
                        }
            
                
                litMedalleroData.Text = sb.ToString();
            }
        }
        #endregion

        #region calendario

        private void LoadCalendarEvents(DateTime date)
        {
            hidDate.Value = date.ToString();
            txtIniDate.Text = date.AddDays(1).Day.ToString("00") + "/" + date.AddDays(1).Month.ToString("00") + "/" + date.AddDays(1).Year;

            int countDays = 14;
            StringBuilder sb = new StringBuilder();
            StringBuilder sb_header = new StringBuilder();
            StringBuilder sb_body = new StringBuilder();

            bool primera = true;
            bool vuelta = false;

            DataSet ds = ReporteManager.GetManager().GetStoreProcedureCalendar(date);

            if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
            {
                //Recorro los deportes
                DataTable dtTemp = ds.Tables[0].DefaultView.ToTable(true, new string[] { "idDeporte", "nombreDeporte" });
                List<string> colors = UtilitiesWeb.getColorsList();
                int index = 0;
                foreach (DataRow r in dtTemp.Rows)
                {
                    if (index > colors.Count - 1) { index = 0; }
                    sb_body.Append("<tr>");
                    for (DateTime d = date; d < date.AddDays(countDays); d = d.AddDays(1))
                    {
                        if (!vuelta)
                        {
                            sb_header.Append(GetCalendarHeadeNode(d, primera));
                        }
                        sb_body.Append(GetCalendarBodyNode(r, primera, d, ds, colors[index]));
                        primera = false;
                    }
                    sb_body.Append("</tr>");
                    index += 1;
                    vuelta = true;
                    primera = true;
                }

                litCalendarHeader.Text = sb_header.ToString();
                litCalendarBody.Text = sb_body.ToString();
            }
        }

        private string GetCalendarHeadeNode(DateTime d, bool primera)
        {
            StringBuilder sb = new StringBuilder();
            if (primera) { sb.Append("<td class='headerInit'></td>"); }
            else
            {
                sb.Append("<td class='headerGeneric'>");
                sb.Append("     <div class='headerMonth'>");
                sb.Append(UtilitiesWeb.getMonthName(d.Month) + "</div>");
                sb.Append("    <div class='headerDay'>");
                sb.Append(d.Day.ToString("00") + "</div>");
                sb.Append("</td>");
            }
            return sb.ToString();
        }

        private DataRow GetEvent(DataSet ds, string deporteId, DateTime d)
        {
            DataRow ret = null;
            string where = "fechahora >= '" + d + "' and fechahora <= '" + d.AddDays(1) + "' and idDeporte = " + deporteId;
            DataRow[] r = ds.Tables[0].Select(where);
            if (r != null && r.Length > 0)
            {
                ret = r[0];
            }
            return ret;
        }

        private string GetCalendarBodyNode(DataRow r, bool primera, DateTime d, DataSet ds, string color)
        {
            DataTable listParticipantes = ds.Tables[1];
            StringBuilder sb = new StringBuilder();
            string deporte = r["nombreDeporte"].ToString();
            string idDeporte = r["idDeporte"].ToString();
            if (primera)
            {
                sb.Append("<td class='eventName'>");
                sb.Append("  <div class='eventColor' style='background-color: " + color + ";'>");
                sb.Append("  </div>");
                sb.Append("  <div class='eventIntName'>");
                sb.Append(deporte);
                sb.Append("  </div>");
                sb.Append("  <div class='clear'>");
                sb.Append("  </div>");
                sb.Append("</td>");
            }
            else
            {
                DateTime dateNow = new DateTime(d.Year, d.Month, d.Day, 0, 0, 0);
                DataRow eRow = GetEvent(ds, idDeporte, dateNow);

                if (eRow == null) { sb.Append("<td></td>"); } //No hay evento para este día
                else
                {
                    DateTime horaDate = Convert.ToDateTime(eRow["fechahora"].ToString());
                    string hora = horaDate.ToShortTimeString();
                    string fecha = horaDate.ToShortDateString();
                    string idEvento = eRow["idEvento"].ToString();

                    sb.Append("<td class='toolTip eventDayCalendar' id='" + idEvento + "'  style='background-color: " + color + "'>");
                    sb.Append(" <img src='Images/medal_gold.png' />");
                    sb.Append(" <div class='dataToolTips' id='tool_" + idEvento + "'>");
                    sb.Append("    <div class='horaToolTips'>");
                    sb.Append(hora + "</div>");
                    sb.Append("    <div class='listTitleToolTips'>");
                    sb.Append("        Lista de Participantes:");
                    sb.Append("    </div>");
                    sb.Append("     <div>");
                    sb.Append(GetListaParticipantes(listParticipantes, int.Parse(idEvento)));
                    sb.Append("     </div>");
                    sb.Append(" </div>");
                    sb.Append("</td>");
                }
            }
            return sb.ToString();
        }

        private string GetListaParticipantes(DataTable table, int eventoId)
        {
            StringBuilder sb = new StringBuilder();

            if (table != null && table.Rows != null)
            {
                DataRow[] foundRows = table.Select("idEvento = " + eventoId);
                sb.Append("<ul>");
                foreach (DataRow r in foundRows)
                {
                    sb.Append("<li>" + r["nombre"].ToString() + "</li>");
                }
                sb.Append("</ul>");
            }
            return sb.ToString();
        }

        protected void lnkNext_Click(object sender, EventArgs e)
        {
            string dateStr = hidDate.Value;
            if (!string.IsNullOrEmpty(dateStr))
            {
                DateTime date = Convert.ToDateTime(dateStr);
                date = date.AddDays(13);
                LoadCalendarEvents(date);
            }
        }

        protected void lnkBack_Click(object sender, EventArgs e)
        {
            string dateStr = hidDate.Value;
            if (!string.IsNullOrEmpty(dateStr))
            {
                DateTime date = Convert.ToDateTime(dateStr);
                date = date.AddDays(-13);
                LoadCalendarEvents(date);
            }
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            DateTime dateNow = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddDays(-1);
            hidDate.Value = dateNow.ToString();
            LoadCalendarEvents(dateNow);
        }

        protected void updateCalendar_Click(object sender, EventArgs e)
        {
            string[] dateIniAux = txtIniDate.Text.Split('/');
            DateTime dateIniValue = new DateTime(Convert.ToInt32(dateIniAux[2]), Convert.ToInt32(dateIniAux[1]), Convert.ToInt32(dateIniAux[0]), 0, 0, 0);
            hidDate.Value = dateIniValue.ToString();
            LoadCalendarEvents(dateIniValue.AddDays(-1));
        }


        #endregion

        #region msg favoritos
        private void LoadMsg(string usrName)
        {
            ParticipanteManager pm = ParticipanteManager.GetManager();
            List<Participante> listPartSeguidos = pm.GetEquiposAtletasSeguidos(usrName);
            StringBuilder sb = new StringBuilder();
            string imgSrc = "";
            string nombreParticipante = "";
            string msg = "";
            foreach (Participante participante in listPartSeguidos)
            {
                List<string> listComentario = participante.Comentarios;
                foreach (string comentario in listComentario)
                {
                    if (string.IsNullOrEmpty("")) { imgSrc = "usuariosinfoto.gif"; }
                    else imgSrc = participante.Foto;
                    nombreParticipante = participante.Nombre;
                    msg = comentario;
                    sb.Append("   <div class='post'>");
                    sb.Append("         <div class='postTitle'>");
                    sb.Append("               <div>");
                    sb.Append("                     <img src='/Images/Participantes/" + imgSrc + "' />");
                    sb.Append("               </div>");
                    sb.Append("               <div class='namePost'>");
                    sb.Append("                     <span>" + nombreParticipante + "</span>");
                    sb.Append("               </div>");
                    sb.Append("                <div class='clear'></div>");
                    sb.Append("         </div>");
                    sb.Append("         <div class='postText'>");
                    sb.Append(msg);
                    sb.Append("         </div>");
                    sb.Append("    </div>");
                }
            }
            litMsgFavotites.Text = sb.ToString();

        }
        #endregion

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        public void cargarGrid()
        {
            GridViewSeguir.DataSource = ParticipanteManager.GetManager().GetAtletasEquipos();
            GridViewSeguir.DataBind();
        }

        protected void lnkAgregar_Click(object sender, EventArgs e)
        {
            ParticipanteManager pm = ParticipanteManager.GetManager();
            List<int> participantesSeguidos = new List<int>();
            foreach (GridViewRow grd_Row in this.GridViewSeguir.Rows)
            {

                CheckBox check = grd_Row.FindControl("myCheckBox") as CheckBox;

                if (check.Checked)
                {
                    int index = grd_Row.DataItemIndex;
                    int id = int.Parse(GridViewSeguir.DataKeys[index].Value.ToString());
                    participantesSeguidos.Add(id);
                }


            }
            int idUsu = ((Usuario)Session["userLogin"]).Id;
            pm.AgregarAtletaEquipoSeguidos(idUsu, participantesSeguidos);
        }
    }
}